package com.test.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网站在线人数：统计session

public class OnlineCountListener implements HttpSessionListener {
    @Override
    //创建session监听：一旦创建Session,就会触发一次这个事件
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        System.out.println(httpSessionEvent.getSession().getId());
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if(onlineCount == null){
            onlineCount = 1;
        }else{
            onlineCount = onlineCount + 1;
        }
        servletContext.setAttribute("OnlineCount", onlineCount);
    }

    @Override
    //销毁session监听：一旦销毁session,就会触发一次这个事件
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if(onlineCount == null){
            onlineCount = 0;
        }else{
            onlineCount = onlineCount - 1;
        }
        servletContext.setAttribute("OnlineCount", onlineCount);
    }
}
